package top.dugou.dugou_sso_server.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.*;
import top.dugou.dugou_sso_server.common.Encryption;
import top.dugou.dugou_sso_server.common.RandomNum;
import top.dugou.dugou_sso_server.common.Result;
import top.dugou.dugou_sso_server.entity.Admin;
import top.dugou.dugou_sso_server.service.AdminService;
import top.dugou.dugou_sso_server.utils.RedisUtil;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 添加用户
     * @param admin
     * @return
     */
    @ApiOperation(value = "添加管理员")
    @ApiResponses({
            @ApiResponse(code = 201,message = "添加成功"),
            @ApiResponse(code = 500,message = "添加失败")
    })
    @RequestMapping(value = "/addAdmin",method = RequestMethod.POST)
    @ResponseBody
    public Map addAdmin(@RequestBody @ApiParam(value = "管理员信息",required = true) Admin admin){
        int res = 0;
        admin.setCreated(new Date());
        admin.setUpdate(new Date());
        res = adminService.addAdmin(admin);
        if(res > 0){
            return Result.instance("201","添加成功").toJsonMap();
        }else{
            return Result.instance("500","添加失败").toJsonMap();
        }
    }

    /**
     * 删除管理员
     * @param id
     * @return
     */
    @ApiOperation("删除管理员")
    @ApiResponses({
            @ApiResponse(code = 204,message = "删除成功"),
            @ApiResponse(code = 500,message = "删除失败")
    })
    @RequestMapping(value = "/delAdmin/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map delAdmin(@PathVariable("id") @ApiParam(value = "管理员主键ID",required = true) Long id){
        int res = 0;
        res = adminService.delAdmin(id);
        if(res > 0){
            return Result.instance("204","删除成功").toJsonMap();
        }else{
            return Result.instance("500","删除失败").toJsonMap();
        }
    }

    /**
     * 修改管理员信息，必须传入主键ID
     * @param admin
     * @return
     */
    @ApiOperation("修改管理员信息，必须传入ID")
    @ApiResponses({
            @ApiResponse(code = 205,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
    @RequestMapping(value = "/updateAdmin",method = RequestMethod.PUT)
    @ResponseBody
    public Map updateAdmin(@RequestBody @ApiParam(value = "管理员信息",required = true)Admin admin){
        int res = 0;
        admin.setUpdate(new Date());
        res = adminService.updateAdmin(admin);
        if(res > 0){
            return Result.instance("205","修改成功").toJsonMap();
        }else{
            return Result.instance("500","修改失败").toJsonMap();
        }
    }

    /**
     * 查询单个管理员信息
     * @param id
     * @return
     */
    @ApiOperation("查询单个管理员信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "查询成功"),
            @ApiResponse(code = 500,message = "查询失败")
    })
    @RequestMapping(value = "/find/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Map findById(@PathVariable("id") @ApiParam(value = "管理员主键ID",required = true) Long id){
        Admin admin = adminService.findById(id);
        if(admin != null){
            return Result.<Admin>instance("200","查询成功",admin).toJsonMap();
        }else{
            return Result.instance("500","查询失败").toJsonMap();
        }
    }

    /**
     * 条件查询
     * @param admin
     * @return
     */
    @ApiOperation("条件查询管理员信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "查询成功"),
            @ApiResponse(code = 500,message = "查询失败")
    })
    @RequestMapping(value = "/select",method = RequestMethod.POST)
    @ResponseBody
    public Map selectByCondition(@RequestBody @ApiParam(value = "管理员信息",required = true) Admin admin){
        List<Admin> list = adminService.selectByCondition(admin);
        if(list.size() > 0){
            return Result.<List<Admin>>instance("200","查询成功",list).toJsonMap();
        }else{
            return Result.instance("500","查询失败").toJsonMap();
        }
    }


    /**
     * 根据时间戳，获取图片验证码，并存入redis里面
     * 存储为key为时间戳，value为imgcode
     * @param timetamp
     * @return
     */
    @ApiOperation(value = "根据时间戳，获取图片验证码")
    @ApiResponses({
            @ApiResponse(code = 200,message = "图片验证码获取成功"),
            @ApiResponse(code = 500,message = "图片验证码获取失败")
    })
    @RequestMapping(value = "/auth/getImgCode/{timetamp}",method = RequestMethod.GET)
    @ResponseBody
    public Map getImgCode(@PathVariable("timetamp") @ApiParam(value = "时间戳",required = true) String timetamp){
        String imgCode = RandomNum.GetRandomString(1000 , 9999);
        if(redisUtil.set("admin"+timetamp, imgCode,60*5)){
            return  Result.<String>instance("200","图片验证码获取成功",imgCode).toJsonMap();
        }else{
            return  Result.instance("500","图片验证码获取失败").toJsonMap();
        }
    }



    @ApiOperation(value = "用户登录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 406,message = "验证失败"),
            @ApiResponse(code = 500,message = "登录失败")
    })
    @RequestMapping(value = "/auth/login/{username}/{password}/{timetamp}/{imgCode}",method = RequestMethod.POST)
    @ResponseBody
    public Map login(
            @PathVariable(value = "username",required = true)   @ApiParam(value = "用户名",required = true)  String username,
            @PathVariable(value = "password",required = true)   @ApiParam(value = "密码",required = true)  String password,
            @PathVariable(value = "timetamp",required = true)   @ApiParam(value = "时间戳",required = true)  String timetamp,
            @PathVariable(value = "imgCode",required = true)   @ApiParam(value = "图片验证码",required = true)  String imgCode
    ){
        if(!redisUtil.hasKey("admin"+timetamp)){
            //redis里面没有验证码失效
            return  Result.instance("406","验证码失效").toJsonMap();
        }else{
            String code = redisUtil.get("admin"+timetamp).toString();
            if(!imgCode.equals(code)){
                //验证码不一致
                return  Result.instance("406","验证码不正确").toJsonMap();
            }else{
                Admin admin  = new Admin();
                admin.setUsername(username);
                admin.setPassword(password);
                List<Admin> list = adminService.selectByCondition(admin);
                if(list.size() > 0){
                    Map<String,Object> res = new HashMap<>();
                    Admin admin1 = list.get(0);
                    res.put("admininfo",admin1);
                    String key = admin1.getUsername()+String.valueOf(System.currentTimeMillis());
                    try {
                        String token =Encryption.md5(key);
                        //登录token  存放着在redis一周
                        if(redisUtil.set("admin"+token,admin1.getId(),60*60*24)){
                            res.put("token","admin"+token);
                            return  Result.<Map<String,Object>>instance("200","登录成功",res).toJsonMap();
                        }else{
                            return  Result.instance("500","登录失败").toJsonMap();
                        }
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }

                }else{
                    return  Result.instance("500","密码或用户名不正确").toJsonMap();
                }
            }
        }
        return Result.instance("500","登录失败").toJsonMap();
    }

    /**
     * 管理员退出登录
     * @param token
     * @return
     */
    @ApiOperation(value = "管理员退出")
    @ApiResponses({
            @ApiResponse(code = 204,message = "退出登录成功"),
            @ApiResponse(code = 205,message = "已退出"),
            @ApiResponse(code = 500,message = "退出登录失败")
    })
    @RequestMapping(value = "/auth/loginout",method = RequestMethod.GET)
    public Map loginout(@RequestParam(value = "token",required = true) @ApiParam(value = "口令token",required = true) String token){

        if(redisUtil.hasKey(token)){
            if(redisUtil.expire(token,1)){
                return Result.instance("204","退出登录成功").toJsonMap();
            }else{
                return Result.instance("500","退出登录失败").toJsonMap();
            }
        }else{
            return Result.instance("205","已退出").toJsonMap();
        }

    }

}
